package binarytree;

import java.util.Stack;

/**
 * @Author: 海琳琦
 * @Date: 2022/2/23 14:40
 * https://leetcode-cn.com/problems/minimum-absolute-difference-in-bst/
 */
public class GetMinimumDifference {

    class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        public TreeNode() {
        }

        public TreeNode(int val) {
            this.val = val;
        }

        public TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    static TreeNode pre;
    static int minGap;
    /**
     * 递归法
     * @param root
     * @return
     */
    public int getMinimumDifference(TreeNode root) {
        pre = null;
        minGap = Integer.MAX_VALUE;
        traversal(root);
        return minGap;
    }

    public void traversal(TreeNode root) {
        if (root != null) {
            traversal(root.left);
            if (pre != null) {
                int gap = root.val - pre.val;
                if (gap < minGap) {
                    minGap = gap;
                }
            }
            pre = root;
            traversal(root.right);
        }
    }

    /**
     * 迭代法
     * @param root
     * @return
     */
    public int getMinimumDifference1(TreeNode root) {
        int minGap = Integer.MAX_VALUE;
        TreeNode pre = null;
        Stack<TreeNode> stack = new Stack<>();
        while (root != null || !stack.isEmpty()) {
            while (root != null) {
                stack.push(root);
                root = root.left;
            }
            root = stack.pop();
            if (pre != null) {
                int gap = root.val - pre.val;
                if (gap < minGap) {
                    minGap = gap;
                }
            }
            pre = root;
            root = root.right;
        }
        return minGap;
    }

    public static void main(String[] args) {

    }
}
